package com.imti.mall.admin.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imti.mall.admin.mapper.UmsAdminMapper;
import com.imti.mall.admin.model.entity.UmsAdmin;
import com.imti.mall.admin.service.UmsAdminService;
import com.imti.mall.common.domain.CommonResult;
import com.imti.mall.common.domain.ResultCode;
import com.imti.mall.common.exception.BusinessException;
import com.imti.mall.common.utils.JwtTokenUtil;
import com.imti.mall.feign.dto.UmsAdminLoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {

    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public CommonResult login(UmsAdminLoginParam umsAdminLoginParam) {
        String token = null;
        //密码需要客户端加密后传递

        //1.正常登录 用户名和密码
        try {
            if(StrUtil.isNotBlank(umsAdminLoginParam.getUsername()) && StrUtil.isNotBlank(umsAdminLoginParam.getPassword())){

                //1.2 比对密码
                UmsAdmin umsAdmin = adminMapper.selectOne(
                    new LambdaQueryWrapper<UmsAdmin>().eq(UmsAdmin::getUsername, umsAdminLoginParam.getUsername()));
                if(ObjectUtil.isNull(umsAdmin)){
                    return CommonResult.failed(ResultCode.VALIDATE_FAILED, "用户名输入错误！");
                } else if (!SecureUtil.md5(umsAdminLoginParam.getPassword()).equals(umsAdmin.getPassword())) {
                    return CommonResult.failed(ResultCode.VALIDATE_FAILED, "密码输入错误！");
                } else {

//                    JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
                    token = jwtTokenUtil.generateToken(umsAdmin.getUsername());
                    return CommonResult.success(token);
                }
            }else {
                //2.未输入信息
                return CommonResult.failed();
            }
        } catch (BusinessException e) {
            log.error("登录异常:{}", e.getMessage());
        }
        return CommonResult.failed();
    }
}
